package com.fanketly.funacg2

import android.app.Application
import android.content.ComponentName
import android.content.Context
import android.content.ServiceConnection
import android.os.IBinder
import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.core.graphics.drawable.toBitmap
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import coil.imageLoader
import coil.request.ImageRequest
import com.fanketly.funacg2.data.PASSWORD
import com.fanketly.funacg2.data.TAG
import com.fanketly.funacg2.data.TOKEN
import com.fanketly.funacg2.data.USERNAME
import com.fanketly.funacg2.utils.ActivityUtils
import com.fanketly.funacg2.utils.ToastUtils
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.lzx.starrysky.SongInfo
import com.lzx.starrysky.StarrySkyInstall
import com.lzx.starrysky.intercept.InterceptCallback
import com.lzx.starrysky.intercept.StarrySkyInterceptor
import com.lzx.starrysky.notification.NotificationConfig
import com.lzx.starrysky.notification.imageloader.ImageLoaderCallBack
import com.lzx.starrysky.notification.imageloader.ImageLoaderStrategy
import com.lzx.starrysky.utils.toSdcardPath
import com.tencent.mmkv.MMKV
import dagger.hilt.android.HiltAndroidApp
import java.text.SimpleDateFormat
import java.util.Locale

@HiltAndroidApp
class App : Application() {
    companion object {
        val sSimpleDateFormat = SimpleDateFormat("yyyy/MM/dd", Locale.CHINA)
        lateinit var sMMKV: MMKV

        // TODO: 持久保存
        var sToken = ""
        lateinit var sApplication: Application
        private val _sServiceConnect = MutableLiveData(false)
        val sServiceConnect: LiveData<Boolean>
            get() = _sServiceConnect
        private val usernameState = mutableStateOf<String?>(null)
        val sUsername
            get() = usernameState.value!!

        fun isLogin() = usernameState.value != null
        fun setUserData(username: String, password: String, token: String) {
            usernameState.value = username
            sToken = token
            sMMKV.encode(USERNAME, username)
            sMMKV.encode(PASSWORD, password)
            sMMKV.encode(TOKEN, token)
        }

        fun logout() {
            usernameState.value = null
            sToken = ""
            sMMKV.remove(USERNAME)
            sMMKV.remove(PASSWORD)
            sMMKV.remove(TOKEN)
        }
    }

    override fun onCreate() {
        super.onCreate()
        sApplication = this
        /*MMKV数据初始化*/
        MMKV.initialize(this)
        sMMKV = MMKV.defaultMMKV()
        usernameState.value = sMMKV.decodeString(USERNAME,null)
        sToken = sMMKV.decodeString(TOKEN, "")!!
        /**/
        val notificationConfig = NotificationConfig.create {
            targetClass { "com.fanketly.funacg2.MainActivity" }
        }
        StarrySkyInstall.init(this)
            .setNotificationSwitch(true)
            .setNotificationConfig(notificationConfig)
            .setImageLoader(CoilImageLoader())
//            .isStartService(true)
//            .onlyStartService(false)
            //            .setAutoManagerFocus(false)   //使用多实例的时候要关掉，不然会相互抢焦点
            .setOpenCache(true)
            .setCacheDestFileDir("000StarrySkyCache/".toSdcardPath())
            .setCacheMaxBytes(1024 * 1024 * 1024)  //设置缓存上限，默认 512 * 1024 * 1024
            .startForegroundByWorkManager(true)
            .connServiceListener(object : ServiceConnection {
                override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                    _sServiceConnect.value = true
//                    val musicServiceBinder = service as MusicServiceBinder
                    Log.i(TAG, "onServiceConnected:$service ")
                }

                override fun onServiceDisconnected(name: ComponentName?) {
                    _sServiceConnect.value = false
                    Log.i(TAG, "onServiceDisconnected: ")
                }

            })
            .addInterceptor(PermissionInterceptor())
            .apply()
    }

    class PermissionInterceptor : StarrySkyInterceptor() {
        override fun process(songInfo: SongInfo?, callback: InterceptCallback) {
            if (songInfo == null) {
                callback.onInterrupt("SongInfo is null")
                return
            }
            ActivityUtils.getTopActivity()?.let {
                XXPermissions.with(it)
                    .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                    .request(object : OnPermissionCallback {
                        override fun onGranted(permissions: List<String>, all: Boolean) {
                            if (all) {
//                                SpConstant.HAS_PERMISSION = true
                                callback.onNext(songInfo)
                            } else {
                                XXPermissions.startPermissionActivity(it, permissions)
                                ToastUtils.shortToast("没有权限，播放失败")
//                                SpConstant.HAS_PERMISSION = false
                            }
                        }

                        override fun onDenied(permissions: List<String>, never: Boolean) {
                            if (never) {
                                XXPermissions.startPermissionActivity(it, permissions)
                            }
//                            SpConstant.HAS_PERMISSION = false
                            callback.onInterrupt("没有权限，播放失败")
                            ToastUtils.shortToast("没有权限，播放失败")
                        }
                    }
                    )
            }

        }

        override fun getTag(): String = "PermissionInterceptor"

    }
//    override fun newImageLoader(): ImageLoader {
//        return ImageLoader.Builder(applicationContext).apply {
//            crossfade(true)
//            placeholder(R.drawable.ic_not_photo)
//            error(R.drawable.ic_not_photo)
//        }.build()
//    }

    class CoilImageLoader : ImageLoaderStrategy {
        override fun loadImage(context: Context, url: String?, callBack: ImageLoaderCallBack) {
            val request = ImageRequest.Builder(context)
                .data(url)
                .target(onSuccess = {
                    callBack.onBitmapLoaded(it.toBitmap())
                })
                .build()
            context.imageLoader.enqueue(request)
        }
    }
}
